package com.gjy.concurrency.h1;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-05-31 09:31:49
 */
public class ThreadUtil {

    private static final Integer CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final Integer IO_MAX = Math.max(2, CPU_COUNT * 2);
    private static final Integer CPU_MAX = CPU_COUNT;
    private static final Integer KEEP_ALIVE_SECONDS = 30;
    private static final Integer QUEUE_SIZE = 128;

    public static ThreadPoolExecutor cpuPool() {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                CPU_MAX,
                CPU_MAX,
                KEEP_ALIVE_SECONDS,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(QUEUE_SIZE),
                new CustomerThreadFactory("CPU")
        );
        pool.allowCoreThreadTimeOut(true);
        Runtime.getRuntime().addShutdownHook(new Thread(pool::shutdown));
        return pool;
    }

    public static ThreadPoolExecutor ioPool() {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                IO_MAX,
                IO_MAX,
                KEEP_ALIVE_SECONDS,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(QUEUE_SIZE),
                new CustomerThreadFactory("IO")
        );
        pool.allowCoreThreadTimeOut(true);
        Runtime.getRuntime().addShutdownHook(new Thread(pool::shutdown));
        return pool;
    }

    private static final class CustomerThreadFactory implements ThreadFactory {

        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final ThreadGroup tg;
        private final String namePrefix;

        public CustomerThreadFactory(String tag) {
            SecurityManager securityManager = System.getSecurityManager();
            tg = (securityManager != null) ? securityManager.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = tag + "-" + poolNumber.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(@NotNull Runnable r) {
            Thread thread = new Thread(tg, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (thread.isDaemon()) {
                thread.setDaemon(false);
            }
            if (thread.getPriority() != Thread.NORM_PRIORITY) {
                thread.setPriority(Thread.NORM_PRIORITY);
            }
            return thread;
        }

    }
}
